﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Converters;
using System.Web.Mvc;
using System.Collections.Specialized;
using OF.Utility;
using System.Web.Mvc.Filters;
using CGT.GOP.Common;
using System.Collections;

namespace CGT.GOP.Controllers
{
    public class BaseController : Controller
    {
        #region 文件下载/上传

        /// <summary>
        /// 根据文件名返回相应的文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [NonAction]
        protected FileResult BaseDownloadFile(string fileName, byte[] fileContents)
        {
            //文件后缀
            string fileExt = fileName.Substring(fileName.LastIndexOf('.'));
            string contentType = "";
            switch (fileExt.ToLower())
            {
                case ".xls":
                case ".xlsx":
                    contentType = "application/x-excel";
                    break;
                case ".doc":
                case ".docx":
                    contentType = "application/msword";
                    break;
                case "gif":
                case "jpeg":
                case "png":
                case "tiff":
                    contentType = "image/" + fileExt.ToLower();
                    break;
                case ".pdf":
                case ".zip":
                case ".xml":
                    contentType = "application/" + fileExt.ToLower();
                    break;
                default:
                    contentType = "text/plain";
                    break;
            }
            FileContentResult fcr = new FileContentResult(fileContents, contentType)
            {
                FileDownloadName = fileName
            };
            return fcr;
        }

        ///// <summary>
        ///// 保存
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //protected string FileSaveAS(HttpPostedFileBase file)
        //{
        //    string target = Server.MapPath("~/Uploads");  //文件路径
        //    string filename = FileHelper.GetFileName(file.FileName);//取得文件名字
        //    string path = FileHelper.AddSlash(target) + filename;//获取存储的目标地址
        //    file.SaveAs(path);
        //    return path;
        //}

        #endregion

        #region 系列化/反序列化

        /// <summary>
        /// 将对象转换成JSON
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected string SerializeObject(object value)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            return JsonConvert.SerializeObject(value, Formatting.Indented, timeFormat);
        }

        /// <summary>
        /// 将JSON字符串转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        protected T DeserializeObject<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }

        #endregion

        #region 重写返回

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Count() > 0)
            {
                return;
            }

            //验证用户是否登陆
            UserInfo usr = FormsPrincipal.IsAuthenticated();
            if (usr == null || usr.UserId == 0)
            {
                filterContext.Result = new RedirectResult(Url.Action("Login","Account"));
            }

            if (!SSOHelper.CheckOnline())
            {
                FormsPrincipal.SignOut();
                filterContext.Result = new RedirectResult(Url.Action("Login", "Account")+ "?msg=您的帐号已在另一地点登录，您被迫下线");
            }

            base.OnAuthentication(filterContext);
        }

        /// <summary>
        /// 重写JsonResult
        /// 由于自带的JsonResult不支持DataTable等对象的序列化
        /// 所以手动构建JsonResult
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        protected ContentResult ReturnResult(object result)
        {
            ContentResult cr = new ContentResult
            {
                ContentType = "application/json",
                Content = SerializeObject(result)
            };
            return cr;
        }

        #endregion

        #region Request参数

        /// <summary>
        /// 获取回传参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetParam(string name)
        {
            string value = "";
            if (Request.HttpMethod == "POST")
            {
                value = Request.Form[name];
                //if (Request.ContentType == "application/json")
                //{
                //    Stream stream = Request.InputStream;
                //    string json = string.Empty;
                //    if (stream.Length != 0)
                //    {
                //        StreamReader streamreader = new StreamReader(stream);
                //        streamreader.BaseStream.Seek(0, SeekOrigin.Begin);
                //        json = streamreader.ReadToEnd();
                //    }
                //    //dynamic ParObject = JsonConvert.DeserializeObject<dynamic>(json);
                //    if (!string.IsNullOrEmpty(json))
                //    {
                //        var pstrArr = json.Split('&');
                //        var paramHash = new Hashtable();
                //        if (pstrArr.Length > 0)
                //        {
                //            foreach (var item in pstrArr)
                //            {
                //                var p = item.Split('=');
                //                //如果传的是'param= '则直接过滤掉。所以==2
                //                if (p.Length == 2)
                //                {
                //                    paramHash.Add(p[0], p[1]);
                //                }
                //            }
                //        }
                //        //按名字接收对应参数
                //        value = Convert.ToString(paramHash[name]);
                //    }
                //}
            }
            if (string.IsNullOrEmpty(value))
            {
                value = Request.QueryString[name];
            }
            if (value == null)
            {
                value = "";
            }
            return value;
        }

        /// <summary>
        /// 获取指定类型参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T GetParam<T>(string name)
        {
            var param = GetParam(name);
            if (string.IsNullOrEmpty(param))
            {
                return default(T);
            }
            return DeserializeObject<T>(param);
        }


        /// <summary>
        /// 获取页码
        /// </summary>
        /// <returns></returns>
        protected int GetPageIndex()
        {
            string page = GetParam("page");
            return EConvert.ToInt(page, 1);
        }

        /// <summary>
        /// 获取页码
        /// </summary>
        /// <returns></returns>
        protected int GetPageSize()
        {
            string rows = GetParam("rows");
            return EConvert.ToInt(rows, 20);
        }

        /// <summary>
        /// 获取前台传递Form
        /// </summary>
        /// <returns></returns>
        protected string GetFormData()
        {
            string sb = "";
            foreach (string key in Request.Form.Keys)
            {
                sb = sb + key + ":" + Request.Form[key] + ",";
            }
            if (sb.Length > 4000)
            {
                return sb.Substring(0, 3999);
            }
            return sb;
        }

        #endregion

        #region 登陆用户
        /// <summary>
        /// 当前登陆用户信息
        /// </summary>
        public UserInfo CurrentUser
        {
            get
            {
                return FormsPrincipal.IsAuthenticated();
            }
        }
        #endregion
    }
}
